package a10_动态规划;

import java.util.Arrays;

/**
 * <p>
 * a16_目标和复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/3/25
 */
public class a16_目标和复习3 {
    //正整数 x
    //负整数 sum - x
    //target = x - (sum - x)
    //x = (target + sum) / 2


    public int findTargetSumWays(int[] nums, int target) {
        int sum = Arrays.stream(nums).sum();
        if((target + sum) % 2 != 0){
            return 0;
        }

        int totalWeight = (target + sum) / 2;

        if(totalWeight < 0){
            return 0;
        }

        int[] dp = new int[totalWeight+1];
        dp[0] = 1;
        for (int i = 0; i < nums.length; i++) {
            for (int j = totalWeight; j >= nums[i]; j--) {
                dp[j] = dp[j] + dp[j - nums[i]];
            }
        }

        return dp[totalWeight];
    }
}
